interface ExchangeRates {
  [key: string]: number;
}

interface ConversionResult {
  from: string;
  to: string;
  amount: number;
  result: number;
  rate: number;
}

// 缓存转换结果，避免频繁请求
type CacheKey = string; // 格式: "FROM_TO_AMOUNT"
type CacheEntry = {
  result: ConversionResult;
  timestamp: number;
};
const conversionCache = new Map<CacheKey, CacheEntry>();
const CACHE_DURATION = 3600000; // 1小时缓存

// 直接使用提供的API进行货币转换
export async function convertCurrencyDirect(
  amount: number,
  fromCurrency: string,
  toCurrency: string
): Promise<number> {
  // console.log('💸 开始直接货币转换:', {
  //   amount,
  //   fromCurrency,
  //   toCurrency
  // });
  
  // 如果货币相同，无需转换
  if (fromCurrency === toCurrency) {
    // console.log('💸 相同货币，无需转换');
    return amount;
  }
  
  // 生成缓存键
  const cacheKey = `${fromCurrency}_${toCurrency}_${amount}`;
  const now = Date.now();
  
  // 检查缓存
  if (conversionCache.has(cacheKey)) {
    const cacheEntry = conversionCache.get(cacheKey)!;
    if (now - cacheEntry.timestamp < CACHE_DURATION) {
      // console.log('💸 使用缓存的转换结果:', cacheEntry.result);
      return cacheEntry.result.result;
    }
  }
  
  try {
    // 使用提供的API进行转换
    const apiKey = '56fb1c10-23b4-38d5-75d1-169e0ec438484eb32930';
    const apiUrl = `https://api.covibe.cn/api/exchange/api.php?apikey=${apiKey}&from=${fromCurrency}&to=${toCurrency}&amount=${amount}&type=json`;
    
    // console.log('💸 调用转换API:', apiUrl);
    
    const response = await fetch(apiUrl, {
      headers: {
        'User-Agent': 'Mozilla/5.0',
        'Accept': '*/*'
      }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    
    const responseData = await response.json();
    // console.log('💸 API返回的直接转换结果:', responseData);
    
    // 检查API返回格式是否正确
    if (!responseData || responseData.code !== 200 || !responseData.data) {
      throw new Error(`无效的API响应: ${JSON.stringify(responseData)}`);
    }
    
    const data = responseData.data;
    
    // 确保结果字段存在并且可以转换为数字
    if (!data.result) {
      throw new Error(`API响应中缺少结果字段: ${JSON.stringify(data)}`);
    }
    
    // 将结果转换为数字
    const convertedAmount = parseFloat(data.result);
    if (isNaN(convertedAmount)) {
      throw new Error(`无法将结果转换为数字: ${data.result}`);
    }
    
    // console.log('💸 直接转换成功:', {
    //   originalAmount: amount,
    //   originalCurrency: fromCurrency,
    //   convertedAmount: convertedAmount,
    //   targetCurrency: toCurrency,
    //   rate: data.rate,
    //   fromName: data.from_name,
    //   toName: data.to_name
    // });
    
    // 缓存结果
    conversionCache.set(cacheKey, {
      result: data,
      timestamp: now
    });
    
    return convertedAmount;
  } catch (error) {
    // console.error('❌ 直接货币转换API调用失败:', error);
    console.error('direct currency conversion API call failed', error);
    
    // 如果转换失败，默认使用日元
    // console.log('💸 转换失败，默认使用日元');
    if (toCurrency === 'JPY') {
      return amount;
    } else {
      // 使用模拟转换作为备用
      return fallbackConversion(amount, fromCurrency, toCurrency);
    }
  }
}

// 为了保持兼容性，保留原来的函数签名
export async function getExchangeRates(baseCurrency: string = 'HKD'): Promise<ExchangeRates> {
  // console.log('💱 获取汇率已被弃用，将使用直接转换API');
  return getMockExchangeRates(baseCurrency);
}

// 为了保持兼容性，保留原来的函数签名
export function convertCurrency(
  amount: number, 
  fromCurrency: string, 
  toCurrency: string, 
  rates: ExchangeRates
): number {
  // console.log('💱 旧的转换函数被调用，将使用直接转换API');
  // 这里我们不能直接返回异步函数的结果，所以使用模拟转换
  return fallbackConversion(amount, fromCurrency, toCurrency);
}

// 模拟转换作为备用方案
function fallbackConversion(amount: number, fromCurrency: string, toCurrency: string): number {
  // console.log('💸 使用模拟转换:', {
  //   amount,
  //   fromCurrency,
  //   toCurrency
  // });
  
  if (fromCurrency === toCurrency) {
    return amount;
  }
  
  // 日元特殊处理，不进行分转换
  if (fromCurrency === 'JPY' || toCurrency === 'JPY') {
    // 使用模拟汇率
    const mockRates = getMockExchangeRates('JPY');
    
    if (fromCurrency === 'JPY') {
      // 从日元转换到其他货币
      return amount * (mockRates[toCurrency] || 1);
    } else {
      // 从其他货币转换到日元
      return amount / (mockRates[fromCurrency] || 1);
    }
  }
  
  // 使用模拟汇率
  const mockRates = getMockExchangeRates('HKD');
  
  // 如果目标货币不在模拟汇率中，返回原始金额
  if (!mockRates[fromCurrency] || !mockRates[toCurrency]) {
    return amount;
  }
  
  // 先转换为HKD，再转换为目标货币
  const amountInHKD = fromCurrency === 'HKD' ? amount : amount / mockRates[fromCurrency];
  const convertedAmount = toCurrency === 'HKD' ? amountInHKD : amountInHKD * mockRates[toCurrency];
  
  // console.log('💸 模拟转换结果:', {
  //   originalAmount: amount,
  //   originalCurrency: fromCurrency,
  //   amountInHKD: amountInHKD,
  //   convertedAmount: convertedAmount,
  //   targetCurrency: toCurrency
  // });
  
  return convertedAmount;
}

// 提供模拟汇率数据，用于API不可用或测试时
function getMockExchangeRates(baseCurrency: string): ExchangeRates {
  // console.log('💱 生成模拟汇率数据，基础货币:', baseCurrency);
  
  // 以JPY为基准的模拟汇率
  const jpyRates: ExchangeRates = {
    USD: 0.0067,   // 1 JPY = 0.0067 USD
    EUR: 0.0062,   // 1 JPY = 0.0062 EUR
    JPY: 1,        // 1 JPY = 1 JPY
    GBP: 0.0053,   // 1 JPY = 0.0053 GBP
    CNY: 0.048,    // 1 JPY = 0.048 CNY
    HKD: 0.052,    // 1 JPY = 0.052 HKD
    TWD: 0.21,     // 1 JPY = 0.21 TWD
    KRW: 9.0,      // 1 JPY = 9.0 KRW
    AUD: 0.010,    // 1 JPY = 0.010 AUD
    CAD: 0.0091,   // 1 JPY = 0.0091 CAD
    SGD: 0.0090,   // 1 JPY = 0.0090 SGD
  };
  
  // 以HKD为基准的模拟汇率
  const hkdRates: ExchangeRates = {
    USD: 0.128,    // 1 HKD = 0.128 USD
    EUR: 0.119,    // 1 HKD = 0.119 EUR
    JPY: 19.2,     // 1 HKD = 19.2 JPY
    GBP: 0.101,    // 1 HKD = 0.101 GBP
    CNY: 0.925,    // 1 HKD = 0.925 CNY
    HKD: 1,        // 1 HKD = 1 HKD
    TWD: 4.06,     // 1 HKD = 4.06 TWD
    KRW: 173.8,    // 1 HKD = 173.8 KRW
    AUD: 0.196,    // 1 HKD = 0.196 AUD
    CAD: 0.175,    // 1 HKD = 0.175 CAD
    SGD: 0.173,    // 1 HKD = 0.173 SGD
  };
  
  // 根据基准货币选择对应的汇率表
  const baseRates = baseCurrency === 'JPY' ? jpyRates : hkdRates;
  
  // 如果基准货币与选择的汇率表匹配，直接返回
  if (baseCurrency === 'JPY' && baseRates === jpyRates || 
      baseCurrency === 'HKD' && baseRates === hkdRates) {
    return baseRates;
  }
  
  // 否则需要转换汇率
  const baseRate = baseRates[baseCurrency];
  if (!baseRate) {
    console.warn('💱 未找到基础货币汇率，回退到默认汇率:', baseCurrency);
    return baseCurrency === 'JPY' ? jpyRates : hkdRates;
  }
  
  // 计算以请求的货币为基准的汇率
  const rates: ExchangeRates = {};
  Object.keys(baseRates).forEach(currency => {
    rates[currency] = baseRates[currency] / baseRate;
  });
  
  return rates;
}